import Web3 from 'web3'

/*
* 1. Check for injected web3 (mist/metamask)
* 2. If metamask/mist create a new web3 instance and pass on result
* 3. Get networkId - Now we can check the user is connected to the right network to use our dApp
* 4. Get user account from metamask
* 5. Get user balance
*/

let getWeb3 = new Promise(function (resolve, reject) {
    //使用promise连接回调方法
    // Check for injected web3 (mist/metamask)检查用户的metamsak
  var web3js = window.web3//metamask注入web3本身的实例
  var web3Provider;
  
  if (typeof web3js !== 'undefined') {
    web3Provider = web3js.currentProvider;
  } else {
    web3Provider = new Web3.providers.HttpProvider('http://127.0.0.1:8545');
    reject(new Error('Unable to connect to Metamask'))
  }
  var web3 = new Web3(web3Provider)
  resolve({
  	injectedWeb3: true, 
  	web3() {
  		return web3
  	}
  })
})
  .then(result => {
    return new Promise(function (resolve, reject) {
      // Retrieve network ID将返回我们连接的网络 ID。
      result.web3().version.getNetwork((err, networkId) => {
        if (err) {
          // If we can't find a networkId keep result the same and reject the promise
          reject(new Error('Unable to retrieve network ID'))
        } else {
          // Assign the networkId property to our result and resolve promise 
  	  	  console.log('retrieve newworkId: ' + networkId)
          result = Object.assign({}, result, {networkId})
          resolve(result)
        }
      })
    })
  })
  .then(result => {
    return new Promise(function (resolve, reject) {
      // Retrieve coinbase返回我们节点挖矿的地址，当使用 Metamask 时，它应该会是已选择的账户。
      result.web3().eth.getCoinbase((err, coinbase) => {
        if (err) {
          reject(new Error('Unable to retrieve coinbase'))
        } else {
          result = Object.assign({}, result, { coinbase })
          resolve(result)
        }
      })
    })
  })
  .then(result => {
    return new Promise(function (resolve, reject) {
      // Retrieve balance for coinbase返回作为参数传入的该地址的余额。
      result.web3().eth.getBalance(result.coinbase, (err, balance) => {
        if (err) {
          reject(new Error('Unable to retrieve balance for address: ' + result.coinbase))
        } else {
          result = Object.assign({}, result, { balance })
          resolve(result)
        }
      })
    })
  })

export default getWeb3